package org.xhnews.ui;

import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import net.rim.device.api.i18n.DateFormat;
import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.picker.DateTimePicker;

import org.xhnews.bo.WeatherBo;
import org.xhnews.preferences.Options;
import org.xhnews.preferences.Preferences;
import org.xhnews.to.City;
import org.xhnews.to.Province;
import org.xhnews.to.RssChannel;
import org.xhnews.utils.StringUtil;

public class SettingsScreen extends MainScreen {
	private ObjectChoiceField _provinces, _cities,_update_interval,_download_type,_store_number,_read_down;
	private Vector v_provinces, v_cities;
	private LabelField _starttime,_endtime;
	public SettingsScreen() {
		setTitle("设置");
		addMenuItem(saveItem);
		Preferences.load();
		add(new LabelField("新闻设置"));
		add(new SeparatorField());
		LabelField _column = new LabelField("    选择栏目", LabelField.FOCUSABLE
				| Field.USE_ALL_WIDTH) {
			protected boolean navigationClick(int status, int time) {
				ColumnSettingScreen screen = new ColumnSettingScreen();
				UiApplication.getUiApplication().pushScreen(screen);
				return true;
			}
		};
		add(_column);
		HorizontalFieldManager _update_period = new HorizontalFieldManager();
		_update_period.add(new LabelField("    下载时段:           "));
		
		_starttime = new LabelField(Preferences.news_update_begin_time, LabelField.FOCUSABLE) {
			protected boolean navigationClick(int status, int time) {
				UiApplication.getUiApplication().invokeLater(new Runnable() {
					public void run() {
						Calendar c=Calendar.getInstance();
						String[] strStartTime=StringUtil.split(_starttime.getText(), ':');
						c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strStartTime[0]));
						c.set(Calendar.MINUTE, Integer.parseInt(strStartTime[1]));
						DateTimePicker datePicker = DateTimePicker
								.createInstance(c, null,
										"HH:mm");
						datePicker.doModal();
						Calendar cal = datePicker.getDateTime();
						Date date = cal.getTime();
						String dateString = new SimpleDateFormat("HH:mm").format(date);
						_starttime.setText(dateString);
					}
				});
				return true;
			}
		};
		_update_period.add(_starttime);
		_update_period.add(new LabelField("--"));
		_endtime = new LabelField(Preferences.news_update_end_time, LabelField.FOCUSABLE) {
			protected boolean navigationClick(int status, int time) {
				UiApplication.getUiApplication().invokeLater(new Runnable() {
					public void run() {
						Calendar c=Calendar.getInstance();
						String[] strEndTime=StringUtil.split(_endtime.getText(), ':');
						c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strEndTime[0]));
						c.set(Calendar.MINUTE, Integer.parseInt(strEndTime[1]));
						DateTimePicker datePicker = DateTimePicker
								.createInstance(Calendar.getInstance(), null,
										"HH:mm");
						datePicker.doModal();
						Calendar cal = datePicker.getDateTime();
						Date date = cal.getTime();
						String dateString = new SimpleDateFormat("HH:mm").format(date);
						_endtime.setText(dateString);
					}
				});
				return true;
			}
		};
		_update_period.add(_endtime);
		add(_update_period);
		_update_interval = new ObjectChoiceField(
				"    下载间隔: ", Options.UPDATE_INTERVAL_LABELS, 1);
		_update_interval.setSelectedIndex(Options.getIndexOfOptions(Preferences.news_update_interval, Options.UPDATE_INTERVAL_VALUES));
		add(_update_interval);
		_download_type = new ObjectChoiceField("    下载类型: ",
				Options.NEWS_DOWNLOAD_TYPE_LABELS, 1);
		_download_type.setSelectedIndex(Options.getIndexOfOptions(Preferences.news_download_type, Options.NEWS_DOWNLOAD_TYPE_VALUES));
		add(_download_type);
		_read_down = new ObjectChoiceField("    已读下沉: ",
				Options.IS_READ_DOWN_LABELS, 1);
		if(Preferences.news_is_readdown)
			_read_down.setSelectedIndex(0);
		else
			_read_down.setSelectedIndex(1);
		add(_read_down);
		 _store_number = new ObjectChoiceField("    存储条数: ",
				Options.NEWS_MAX_COUNT_LABELS, 1);
		_store_number.setSelectedIndex(Options.getIndexOfOptions(Preferences.news_max_count_per_channel, Options.NEWS_MAX_COUNT_VALUES));
		add(_store_number);
		add(new SeparatorField());
		add(new LabelField("天气设置"));
		add(new SeparatorField());
		_provinces = new ObjectChoiceField("    选择省份: ",
				Options.NEWS_DOWNLOAD_TYPE_LABELS, 1);
		add(_provinces);
		_cities = new ObjectChoiceField("    选择城市: ",
				Options.NEWS_DOWNLOAD_TYPE_LABELS, 1);
		add(_cities);
		add(new SeparatorField());
		LabelField _contactus = new LabelField("关于", LabelField.FOCUSABLE
				| Field.USE_ALL_WIDTH) {
			protected boolean navigationClick(int status, int time) {
				AboutScreen screen = new AboutScreen();
				UiApplication.getUiApplication().pushScreen(screen);
				return true;
			}
		};
		add(_contactus);
		_provinces.setChoices(loadProvinces());
		_provinces.setSelectedIndex(this.getIndexOfProvinces(Preferences.location_province_id, v_provinces));
		_provinces.setChangeListener(_provinces_listener);
		_cities.setChoices(loadCites(Preferences.location_province_id));
		_cities.setSelectedIndex(this.getIndexOfCities(Preferences.location_city_code, v_cities));
	}

	private String[] loadProvinces() {
		v_provinces = WeatherBo.getProvinces();
		String[] s_provinces = new String[v_provinces.size()];
		for (int i = 0; i < s_provinces.length; i++) {
			s_provinces[i] = ((Province) v_provinces.elementAt(i)).getName();
		}
		return s_provinces;
	}

	private String[] loadCites(int provinceID) {
		v_cities = WeatherBo.getCities(provinceID);
		String[] s_cities = new String[v_cities.size()];
		for (int i = 0; i < s_cities.length; i++) {
			s_cities[i] = ((City) v_cities.elementAt(i)).getName();
		}
		return s_cities;
	}

	FieldChangeListener _provinces_listener = new FieldChangeListener() {
		public void fieldChanged(Field field, int context) {
			if (field instanceof ObjectChoiceField) {
				Province p = (Province) v_provinces
						.elementAt(((ObjectChoiceField) field)
								.getSelectedIndex());
				final int id = p.getId();
				_cities.setChoices(loadCites(id));
			}
		}
	};

	public int getIndexOfProvinces(int id,Vector provinces){
		for(int i=0;i<provinces.size();i++){
			int pid=((Province)provinces.elementAt(i)).getId();
			if(pid==id)return i;
		}			
		return 0;
	}
	public int getIndexOfCities(int code,Vector cities){
		for(int i=0;i<cities.size();i++)
			if(((City)cities.elementAt(i)).getCode()==code)return i;
		return 0;
	}
	public MenuItem saveItem = new MenuItem("保存", 110, 10) {
		public void run() {

			Preferences.news_update_begin_time=_starttime.getText();
			Preferences.news_update_end_time=_endtime.getText();
			
			Preferences.news_update_interval = Options.UPDATE_INTERVAL_VALUES[_update_interval
					.getSelectedIndex()];

			Preferences.news_download_type = Options.NEWS_DOWNLOAD_TYPE_VALUES[_download_type
					.getSelectedIndex()];

			Preferences.news_is_readdown = Options.IS_READ_DOWN_VALUES[_read_down
					.getSelectedIndex()];

			Preferences.news_max_count_per_channel = Options.NEWS_MAX_COUNT_VALUES[_store_number
					.getSelectedIndex()];

			City c = (City) v_cities.elementAt(_cities.getSelectedIndex());
			Preferences.location_city_code = c.getCode();
			Preferences.location_city_id = c.getId();
			Preferences.location_city_name = c.getName();
			Preferences.location_province_id = c.getProvinceID();
			Preferences.save();
		}
	};
}
